package top.kaoshanji.r2ch07e;

import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.support.DelegatingIntroductionInterceptor;

/**
 * 代码清单-r2ch07e-240页b：定义一个引介增强
 * @author kaoshanji
 * ^_^
 * create time 2025/5/7 18:19
 */
public class ControllablePerformanceMonitor extends DelegatingIntroductionInterceptor implements Monitorable {

    // 因为 active 是有状态的，会出现线程安全问题，放在 ThreadLocal 里面就可以不需要定义原型Bean而实现线程安全了
    private ThreadLocal<Boolean> monitorStatusMap = new ThreadLocal<>();

    @Override
    public void setMonitorActive(boolean active) {
        monitorStatusMap.set(active);
    }

    @Override
    public Object invoke(MethodInvocation mi) throws Throwable {
        Object obj = null;

        // 对于支持性能监视可控代理，通过判断其状态决定是否开启性能监控功能
        if (monitorStatusMap.get() != null && monitorStatusMap.get()) {
            PerformanceMonitor.begin(mi.getClass().getName() + "." + mi.getMethod().getName());

            obj = super.invoke(mi);

            PerformanceMonitor.end();
        } else {
            obj = super.invoke(mi);
        }

        return obj;
    }
}

